<template>
  <div class="parent-container">
    <div
      class="centered-element"
      ref="chartsDOM"
      style="width: 100%; height: 100%; background-color: #f0f0f0"
    >
      <!-- 图表内容 -->
    </div>
  </div>
</template>

<script setup>
import * as echarts from "echarts";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { getGuangdongMap } from "../../api/map/getGuangdongMap";
import { getTopProductionCities } from "@/api/map/getCityTotalOutput";

const chartsDOM = ref(null);
const cityProduction = ref({});
const router = useRouter();

onMounted(async () => {
  if (!chartsDOM.value) return;

  const myChart = echarts.init(chartsDOM.value);
  myChart.showLoading();

  try {
    const [geoData, productionData] = await Promise.all([
      getGuangdongMap(),
      getTopProductionCities(),
    ]);

    cityProduction.value = productionData.data.reduce((acc, item) => {
      acc[item.city] = item.totalOutput;
      return acc;
    }, {});

    if (!geoData?.features?.length) {
      throw new Error("获取到的地图数据为空或不完整");
    }

    echarts.registerMap("GD", geoData);
    const maxProduction = Math.max(
      ...productionData.data.map((item) => item.totalOutput)
    );

    const option = {
      title: {
        text: "粤西荔枝产区分布",
        subtext: "数据来自实际产量(吨)",
        left: "center",
      },
      tooltip: {
        trigger: "item",
        formatter: (params) => {
          const production = cityProduction.value[params.name] || 0;
          return `<strong>${params.name}</strong><br/>荔枝产量: ${production}吨`;
        },
      },
      visualMap: {
        min: 0,
        max: maxProduction,
        inRange: {
          color: ["#f0f9e8", "#bae4bc", "#7bccc4", "#43a2ca", "#0868ac"],
        },
      },
      series: [
        {
          name: "粤西荔枝",
          type: "map",
          map: "GD",
          roam: true,
          label: { show: true },
          data: geoData.features.map((feature) => ({
            name: feature.properties.name,
            value: cityProduction.value[feature.properties.name] || 0,
            itemStyle: {
              areaColor: getAreaColor(
                cityProduction.value[feature.properties.name]
              ),
            },
          })),
          emphasis: {
            label: { color: "#fff" },
            itemStyle: { areaColor: "#c23531" },
          },
          selectedMode: "single",
        },
      ],
    };

    myChart.setOption(option);

    // 添加点击事件监听
    /**
     * 地图点击事件处理函数
     *
     * 当用户点击地图系列时，根据点击的城市名称导航到城市详情页，
     * 并携带城市名称和对应的产量数据作为查询参数。
     *
     * @param {Object} params - ECharts点击事件参数对象
     * @param {string} params.componentType - 组件类型，检查是否为'series'
     * @param {string} params.seriesType - 系列类型，检查是否为'map'
     * @param {string} params.name - 点击的城市名称
     */
    myChart.on("click", (params) => {
      // 检查点击的是地图系列
      if (params.componentType === "series" && params.seriesType === "map") {
        const cityName = params.name;

        // 导航到城市详情页，携带城市名称和产量数据
        router.push({
          path: "/city-detail",
          query: {
            city: encodeURIComponent(cityName), // 编码城市名称防止特殊字符问题
            production: cityProduction.value[cityName] || 0, // 获取该城市产量，默认0
          },
        });
      }
    });
  } catch (error) {
    console.error("加载失败:", error);
    myChart.setOption({
      title: {
        text: "数据加载失败",
        subtext: error.message,
        left: "center",
        top: "center",
      },
    });
  } finally {
    myChart.hideLoading();
  }
});

function getAreaColor(production) {
  if (!production) return "#f5f5f5";
  if (production > 4000) return "#c23531";
  if (production > 3000) return "#dd6b66";
  if (production > 2000) return "#91d5ff";
  return "#f5f5f5";
}
</script>

<style scoped>
.parent-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  padding: 20px;
  box-sizing: border-box;
}

.centered-element {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}
</style>